package my.jwds.p38;

public class CountAndSay {
    public static void main(String[] args) {
        System.out.println(countAndSay(30));
    }

    public static String countAndSay(int n) {
        String num = "1";
        for (;n > 1; n--) {
            num = countString(num);
        }
        return num;
    }


    public static String countString(String prev){
        StringBuilder sb = new StringBuilder();
        int count = 1,length = prev.length();
        char indexChar = prev.charAt(0);
        for (int i = 1; i < length; i++) {
            if (indexChar != prev.charAt(i)){
                sb.append(count);
                sb.append(indexChar);
                count = 0;
            }
            indexChar = prev.charAt(i);
            count ++;
        }
        sb.append(count);
        sb.append(indexChar);
        return sb.toString();
    }

    public static String countAndSayLong(int n) {
        long num = 1l;
        for (;n > 1; n--) {
            num = count(num);
            System.out.println(num);
        }
        return String.valueOf(num);
    }


    public static long count(long prev){
        long now = 0,temp = -1,multiple = 1,eqCount = 0;

        while(prev != 0){
            if (eqCount != 0 && temp != prev % 10){
                now += (eqCount*10+temp)*multiple;
                multiple *= 100;
                eqCount = 0;
            }
            temp = prev % 10;
            prev/= 10;
            eqCount++;
        }
        now += (eqCount*10+temp)*multiple;
        return now;
    }
}
